package com.cmc.rabbitMq;

import com.alibaba.fastjson.JSON;
import com.cmc.constant.MqQueueConstant;
import com.cmc.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author chengmingchao
 */
@Component
@Slf4j
public class RabbitMqUtil {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * rabbitmq发送消息
     * @param routingKey
     * @param message
     */
    public void send(String routingKey,String message){
        log.info("routingKey===>{},message====>{}",routingKey,message);
        rabbitTemplate.convertAndSend(routingKey,message);
    }

    /**
     * rabbitmq接受消息，存入redis或更新
     */
    @RabbitListener(queues = MqQueueConstant.INSERT_UPDATE)
    public void insert_update(String message){
        log.info("接受到消息====>{}",message);
        User user = JSON.parseObject(message, User.class);
        String key="user"+user.getId();
        redisTemplate.opsForValue().set(key,user);
    }

    /**
     * rabbitmq接受消息，删除redis的key
     * @param message
     */
    @RabbitListener(queues = MqQueueConstant.DELETE)
    public void delete(String message){
        log.info("接受到消息====>{}",message);
        User user = JSON.parseObject(message, User.class);
        String key="user"+user.getId();
        redisTemplate.delete(key);
    }

}
